import java.util.*;

class MyTimerTask implements Comparable<MyTimerTask>{
     private Runnable runnable;
    //此处的time,通过毫秒时间戳,表示这个任务具体什么时候执行
     private long time;

     public MyTimerTask(Runnable runnable,long delay){

         this.runnable = runnable;
         this.time=System.currentTimeMillis() + delay;

     }
     public void run(){
         runnable.run();
     }
     public long getTime(){

         return time;
     }

    @Override
    public int compareTo(MyTimerTask o) {
         //此处判断大小堆
        return (int)(this.time-o.time);
    }
}
class MyTimer{
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask> queue =new PriorityQueue<>();
    public MyTimer(){


    //创建线程,负责执行上述队列内容
    Thread t= new Thread(()->{
        try {
            while (true) {
                synchronized (locker){
                    while (queue.isEmpty()) {
                        locker.wait();

                    }

                MyTimerTask current = queue.peek();
                if (System.currentTimeMillis() >= current.getTime()) {
                    //执行任务
                    current.run();
                    //把执行过的任务,从队列删除
                    queue.poll();

                } else {
                    //不执行任务
                    //不能用sleep,sleep不会释放锁,抱着锁睡,其他人拿不到offer不了
                    locker.wait(current.getTime() - System.currentTimeMillis());
                }}
            }

        } catch (InterruptedException e) {
            e.printStackTrace();

       }
    });
    t.start();
    }
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
        MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
        queue.offer(myTimerTask);
        locker.notify();
        }
    }

}


public class demo {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()->{
            System.out.println("hello 3000");

        },3000);
        myTimer.schedule(()->{
            System.out.println("hello 2000");

        },2000);
        myTimer.schedule(()->{
            System.out.println("hello 1000");

        },1000);
        System.out.println("程序开始");

    }


}
